package com.wjx.shoolnews.service;

import com.wjx.shoolnews.Utils.JwtUtils;
import com.wjx.shoolnews.mapper.ordinaryuserMapper;
import com.wjx.shoolnews.pojo.CommonResult;
import com.wjx.shoolnews.pojo.OrdinaryUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//import javax.security.auth.message.callback.SecretKeyCallback;
//import javax.servlet.http.HttpSession;
//import javax.websocket.Session;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdinaryUserImpl implements OrdinaryUserService {

    @Autowired
    ordinaryuserMapper ordinaryUsermapper;
    @Override
    public CommonResult getOrdinaryUser(String zhanghao,String password) {
        String password1=null;
        String nickname=null;
        List<OrdinaryUser> ordinaryUser = ordinaryUsermapper.getOrdinaryUser(zhanghao);
        if(!ordinaryUser.isEmpty()){
            for (OrdinaryUser user : ordinaryUser) {
                 password1 = user.getPassword();
                nickname=user.getNickname();
                if(password.equals(password1)){
                    Map<String, String> map = new HashMap<String,String>();
                    map.put("zhanghao",zhanghao);
                    map.put("nickname",nickname);
                    //生成令牌
                    try {
                        String token = JwtUtils.getToken(map);
                        return new CommonResult(200,"登录成功",token);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }


                }
                else {
                    return new CommonResult(401,"登录失败，密码错误！");
                }
            }

        }

        return new CommonResult(401,"未注册或者账号输入错误");
    }

    @Override
    public CommonResult register(OrdinaryUser ordinaryUser) {

        List<OrdinaryUser> ordinaryUser1 = ordinaryUsermapper.getOrdinaryUser(ordinaryUser.getZhanghao().trim());
        if(!ordinaryUser1.isEmpty()){
            return new CommonResult(401,"注册失败，该账号已经被注册，请重新注册！");
        }
        int register = ordinaryUsermapper.register(ordinaryUser);

        if(register>0){
            return new CommonResult(400,"注册成功");
        }

        return new CommonResult(401,"注册失败，请重新注册！");

    }
}
